import axios from 'axios'

// 跨域带 cookie
axios.defaults.withCredentials = true


async function ajaxGet(url = '', params = {}) {
  return await axios.get(url, params)
    .then(res => res.data)
    .catch(error => {
      if (error.code === 'ECONNABORTED') return { ok: false, message: 'timeout of 1000ms exceeded' }
      return error.response.data
    })
}

async function ajaxPost(url = '', data = {}) {
  const config = { headers: { 'Content-Type': 'application/json' }, timeout: 1000 } // timeout: 1000 ==>>设置请求超时时间是1秒
  /*
   // 服务器内部错误,500是后端定义的  error.status ===500 error.code = 'ERR_BAD_RESPONSE'
   只有3种情况:
      1-请求成功
      2-请求超时(未到服务端或服务端处理超时) 此时; error.code === 'ECONNABORTED'
      3-请求异常; 服务端处理报错,返回的status=500
   */
  return await axios.post(url, data, config)
    .then(res => res.data)
    .catch(error => {
      if (error.code === 'ECONNABORTED') return { ok: false, message: 'timeout of 1000ms exceeded' }
      return error.response.data
    })
}

export { ajaxGet, ajaxPost }
